#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

void diep(char *s)
{
  perror(s);
  exit(1);
}

int main(int argc, char **argv)
{
  struct sockaddr_in si_other;
  int s, i, c, slen=sizeof(si_other);
  char *buf;

  char *host = "127.0.0.1";
  int port = 9930;
  int buflen = 8192;
  int num_bytes = 1000000;
  int iter;

  while((c = getopt(argc, argv, "l:p:n:c:")) != -1) {
    switch(c) {
    case 'l':
      buflen = atoi(optarg);
      break;

    case 'p':
      port = atoi(optarg);
      break;

    case 'c':
      host = strdup(optarg);
      break;

    case 'n':
      num_bytes = atoi(optarg);
      break;
    }
  }  

  buf = malloc(buflen*sizeof(char));
  iter = num_bytes/buflen;

  if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
    diep("socket");
  
  memset((char *) &si_other, 0, sizeof(si_other));
  si_other.sin_family = AF_INET;
  si_other.sin_port = htons(port);
  if (inet_aton(host, &si_other.sin_addr)==0) {
    fprintf(stderr, "inet_aton() failed\n");
    exit(1);
  }
  
  for (i=1; i<=iter; i++) {
    //printf("Sending packet %d\n", i);

    if (i==iter)
      sprintf(buf, "%d", 0);
    else
      sprintf(buf, "%d", i);

    if (sendto(s, buf, buflen, 0, &si_other, slen)==-1)
      diep("sendto()");

  }
  
  close(s);
  return 0;
}
